package com.changyi.device.swipe;

import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;

import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;
import com.sunmi.pay.hardware.aidlv2.readcard.CheckCardCallbackV2;
import com.sunmi.pay.hardware.aidlv2.readcard.ReadCardOptV2;

import sunmi.paylib.SunmiPayKernel;

public class SunmiP2Card implements ReadCardInterface {

    private Context mContext;
    private static SunmiP2Card sunmiP2Card;
    private static ReadCardOptV2 mReadCardOptV2;
    private SunmiPayKernel mSMPayKernel;
    private ReadCardResultInterface readCardResultInterface;
    private SunmiP2Card(Context context) {
        mContext = context;
        mSMPayKernel = SunmiPayKernel.getInstance();
        mSMPayKernel.initPaySDK(mContext, mConnectCallback);
    }

    public static SunmiP2Card getInstance(Context context) {
        if (sunmiP2Card == null) {
            synchronized (SunmiP2Card.class){
                if (sunmiP2Card == null) {
                    sunmiP2Card = new SunmiP2Card(context);
                }
            }
        }
        return sunmiP2Card;
    }

    private SunmiPayKernel.ConnectCallback mConnectCallback = new SunmiPayKernel.ConnectCallback() {

        @Override
        public void onConnectPaySDK() {
            Log.e("TAG", "onConnectPaySDK");
            mReadCardOptV2 = mSMPayKernel.mReadCardOptV2;
            checkCard();
        }

        @Override
        public void onDisconnectPaySDK() {
            Log.e("TAG", "onDisconnectPaySDK");
        }

    };

    /** start check card */
    private void checkCard() {
        try {
            mReadCardOptV2.checkCard(AidlConstantsV2.CardType.NFC.getValue() | AidlConstantsV2.CardType.IC.getValue()| AidlConstantsV2.CardType.MAGNETIC.getValue(), mCheckCardCallback, 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CheckCardCallbackV2 mCheckCardCallback = new CheckCardCallbackV2Wrapper() {
        /**
         * Find magnetic card
         *
         * @param info return data，contain the following keys:
         *             <br/>cardType: card type (int)
         *             <br/>TRACK1: track 1 data (String)
         *             <br/>TRACK2: track 2 data (String)
         *             <br/>TRACK3: track 3 data (String)
         *             <br/>track1ErrorCode: track 1 error code (int)
         *             <br/>track2ErrorCode: track 2 error code (int)
         *             <br/>track3ErrorCode: track 3 error code (int)
         *             <br/> track error code is one of the following values:
         *             <ul>
         *             <li>0 - No error</li>
         *             <li>-1 - Track has no data</li>
         *             <li>-2 - Track parity check error</li>
         *             <li>-3 - Track LRC check error</li>
         *             </ul>
         */
        @Override
        public void findMagCard(Bundle info) throws RemoteException {
            if(info!=null) {
                Log.e("TAG", "findMagCard,bundle:" + Utility.bundle2String(info));
                handleResult(info);
            }else{
                if(readCardResultInterface!=null)
                    readCardResultInterface.cardResultFail("磁道无数据!");
            }
        }

        @Override
        public void findICCard(String atr) throws RemoteException {
            Log.e("TAG", "findICCard,atr:" + atr);
        }

        @Override
        public void findRFCard(String uuid) throws RemoteException {
            Log.e("TAG", "findRFCard,uuid:" + uuid);
        }

        @Override
        public void findRFCardEx(Bundle info) throws RemoteException {
            Log.e("TAG", "findRFCard,ats:" +   info.getString("ats"));
            Log.e("TAG", "findRFCard,atqa:" +   info.getByte("atqa"));
            super.findRFCardEx(info);
        }

        @Override
        public void onError(int code, String message) throws RemoteException {
            String error = "onError:" + message + " -- " + code;
            if(readCardResultInterface!=null)
                readCardResultInterface.cardResultFail(message);
        }
    };

    private void handleResult(Bundle bundle) {
            String track1 = Utility.null2String(bundle.getString("TRACK1"));
            String track2 = Utility.null2String(bundle.getString("TRACK2"));
            String track3 = Utility.null2String(bundle.getString("TRACK3"));
            //磁道错误码：0-无错误，-1-磁道无数据，-2-奇偶校验错，-3-LRC校验错
            int code1 = bundle.getInt("track1ErrorCode");
            int code2 = bundle.getInt("track2ErrorCode");
            int code3 = bundle.getInt("track3ErrorCode");
            if(readCardResultInterface!=null){
                if(code1==0){
                    readCardResultInterface.cardResultSucsses(track1);
                }else if(code2==0){
                    readCardResultInterface.cardResultSucsses(track2);
                }else if(code3==0) {
                    readCardResultInterface.cardResultSucsses(track3);
                }else{
                    readCardResultInterface.cardResultFail("磁道无数据!");
                }
            }
    }

    @Override
    public ReadCardInterface init() {
        if(mReadCardOptV2!=null)
        checkCard();
        return sunmiP2Card;
    }

    @Override
    public ReadCardInterface close() {
        try {
            mReadCardOptV2.cancelCheckCard();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sunmiP2Card;
    }

    @Override
    public ReadCardInterface setReadCardResult(ReadCardResultInterface readCardResultInterface) {
        this.readCardResultInterface = readCardResultInterface;
        return sunmiP2Card;
    }

}
